package com.colin.juc.atomic;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by Colin on 2020/4/19 16:58
 * email: colinzhaodong@gmail.com
 * desc: 演示高并发场景下，LongAdder比AtomicLong性能好
 *
 * @author zhaod
 */
public class AtomicLongDemo {
	public static void main(String[] args) {
		AtomicLong counter = new AtomicLong(0);
		ExecutorService executorService = new ThreadPoolExecutor(20, 20, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				return new Thread(r, "colin-thread");
			}
		});
		long start = System.currentTimeMillis();
		for (int i = 0; i < 10000; i++) {
			executorService.submit(new Task(counter));
		}
		executorService.shutdown();
		while (!executorService.isTerminated()) {
		}
		long end = System.currentTimeMillis();
		System.out.println(counter.get());
		System.out.println("AtomicLong耗时：" + (end - start));

	}

	private static class Task implements Runnable {

		private final AtomicLong counter;

		public Task(AtomicLong counter) {
			this.counter = counter;
		}

		@Override
		public void run() {
			for (int i = 0; i < 10000; i++) {
				counter.incrementAndGet();
			}
		}
	}
}
